<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>2018/11/30</title>
    <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
    <!--好的代码像粥一样,是得用时间和精力熬的。-->
</head>
<body>
<button id="sum">计算</button>
<script>
    let btn = document.getElementById('sum');
    let request = config => new Promise((resolve,reject) =>{
        $.ajax({
            url: config.url,
            method: config.method || 'get',
            data: config.params,
            success(data) {data.code == 1 ? resolve(data) : reject(data);},
            fail(error) { reject(error);}
        })
    });
    btn.onclick = function() {
        // request({method: 'get', url: 'http://10.10.25.174:8080/a', params: {a: 1}})
        //     .then(function (data) {
        //         res += data.value;
        //         return request({method: 'get', url: 'http://10.10.25.174:8080/b', params: {a: 2}})
        //     })
        //     .then(function (data) {
        //         res += data.value;
        //         return request({method: 'get', url: 'http://10.10.25.174:8080/c', params: {a: 3}})
        //     })
        //     .then(function (data) {
        //         res += data.value;
        //         return request({method: 'get', url: 'http://10.10.25.174:8080/d', params: {a: 4}})
        //     })
        //     .then(function (data) {
        //         res += data.value;
        //         console.log(res);
        //         res = 0;
        //     })
        //     .catch(function(error){console.log(error)]});


        Promise.all([
            request({url:'http://10.10.25.174:8080/a',params:{a:1}}),
            request({url:'http://10.10.25.174:8080/b',params:{a:2}}),
            request({url:'http://10.10.25.174:8080/c',params:{a:3}}),
            request({url:'http://10.10.25.174:8080/d',params:{a:4}}),
        ]).then((data) => console.log(data.reduce((prev,current) => prev + current.value,0)));

    }
        function request(config) {
            return new Promise(function (resolve, reject) {
                $.ajax({
                    url: config.url,
                    method: config.method,
                    data: {a: 1},
                    success: function (data) {
                        if (data.code == 1) {
                            resolve(data);
                        } else {
                            reject(data);
                        }

                    },
                    fail: function (error) {
                        console.log(error);

                    },
                })
            });
        }


</script>
</body>
</html>
